package br.com.dwii.tpg2.util;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Diego
 */
public class DBUtil {
    
    private static String driver;
    private static String urlConn;
    private static final String DBIP = "localhost";
    private static final String DBPORT = "3306";
    private static final String PROTOCOL = "jdbc:mysql:";
    private static final String DBNAME = "DWII_TPG2";
    private static final String DBUSER = "root";
    private static final String DBPASS = "gabi";

    static {
        driver = "com.mysql.jdbc.Driver";
        urlConn = PROTOCOL + "//" + DBIP + ":" + DBPORT + "/" + DBNAME;
        loadDriver();
    }

    // Carrega o driver do banco de dados
    public static void loadDriver() {
        try {
            Class.forName(driver).newInstance();
        } catch (ClassNotFoundException cnfe) {
            Logger.getLogger(DBUtil.class.getName()).log(Level.SEVERE, null, cnfe);
        } catch (InstantiationException ie) {
            Logger.getLogger(DBUtil.class.getName()).log(Level.SEVERE, null, ie);
        } catch (IllegalAccessException iae) {
            Logger.getLogger(DBUtil.class.getName()).log(Level.SEVERE, null, iae);
        }
    }

    // Estabelece conexao com o banco de dados
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(urlConn, DBUSER, DBPASS);
        } catch (SQLException ex) {
            Logger.getLogger(DBUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        return conn;
    }
    
    public static Long lastInsertedId(String table) throws SQLException {
        Connection conn = DBUtil.getConnection();
        Statement s = null;
        ResultSet rs = null;
        Long ret = 0L;
        try {
            s = conn.createStatement();
            rs = s.executeQuery("select max(id) from " + table);
            if (rs.next()) {
                ret = rs.getLong(1);
            }
        } catch (SQLException ex) {
            Logger.getLogger(DBUtil.class.getName()).log(Level.SEVERE, null, ex);
            throw ex;
        } finally {
            s.close();
            rs.close();
            conn.close();
        }
        return ret;
    }
}
